<template>
  <div class="log-management">
    <div class="page-header">
      <h1 class="page-title">日志管理</h1>
      <div class="header-actions">
        <el-button type="danger" @click="clearLogs">
          <i class="fas fa-trash mr-2"></i>清空日志
        </el-button>
        <el-button type="success" @click="exportLogs">
          <i class="fas fa-download mr-2"></i>导出日志
        </el-button>
        <el-button type="primary" @click="refreshData">
          <i class="fas fa-sync-alt mr-2"></i>刷新
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-section">
      <div class="search-row">
        <el-input
          v-model="searchQuery"
          placeholder="搜索用户、操作或IP地址"
          class="search-input"
          clearable
        >
          <template #prefix>
            <i class="fas fa-search"></i>
          </template>
        </el-input>
        <el-select v-model="levelFilter" placeholder="日志级别" clearable class="level-filter">
          <el-option label="全部" value=""></el-option>
          <el-option label="信息" value="info"></el-option>
          <el-option label="警告" value="warning"></el-option>
          <el-option label="错误" value="error"></el-option>
          <el-option label="调试" value="debug"></el-option>
        </el-select>
        <el-select v-model="moduleFilter" placeholder="模块" clearable class="module-filter">
          <el-option label="全部" value=""></el-option>
          <el-option label="用户管理" value="user"></el-option>
          <el-option label="案件管理" value="case"></el-option>
          <el-option label="系统管理" value="system"></el-option>
          <el-option label="认证授权" value="auth"></el-option>
        </el-select>
        <el-date-picker
          v-model="dateRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          class="date-picker"
        />
        <el-button type="primary" @click="handleSearch">搜索</el-button>
      </div>
    </div>

    <!-- 统计信息 -->
    <div class="stats-section">
      <div class="stat-card total">
        <div class="stat-icon">
          <i class="fas fa-list-alt"></i>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ stats.totalLogs }}</div>
          <div class="stat-label">总日志数</div>
        </div>
      </div>
      <div class="stat-card today">
        <div class="stat-icon">
          <i class="fas fa-calendar-day"></i>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ stats.todayLogs }}</div>
          <div class="stat-label">今日日志</div>
        </div>
      </div>
      <div class="stat-card errors">
        <div class="stat-icon">
          <i class="fas fa-exclamation-triangle"></i>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ stats.errorLogs }}</div>
          <div class="stat-label">错误日志</div>
        </div>
      </div>
      <div class="stat-card active">
        <div class="stat-icon">
          <i class="fas fa-users"></i>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ stats.activeUsers }}</div>
          <div class="stat-label">活跃用户</div>
        </div>
      </div>
    </div>

    <!-- 日志列表 -->
    <div class="logs-section">
      <div class="section-header">
        <h2 class="section-title">系统日志</h2>
        <div class="view-controls">
          <el-switch
            v-model="autoRefresh"
            active-text="自动刷新"
            inactive-text="手动刷新"
          />
        </div>
      </div>

      <el-table :data="filteredLogs" v-loading="loading" style="width: 100%" stripe>
        <el-table-column prop="timestamp" label="时间" width="180"></el-table-column>
        <el-table-column prop="level" label="级别" width="80" align="center">
          <template #default="{ row }">
            <el-tag :type="getLevelType(row.level)" size="small">
              {{ getLevelText(row.level) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="module" label="模块" width="100">
          <template #default="{ row }">
            <el-tag type="info" size="small">{{ getModuleText(row.module) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="user" label="用户" width="120"></el-table-column>
        <el-table-column prop="action" label="操作" width="150"></el-table-column>
        <el-table-column prop="ip" label="IP地址" width="120"></el-table-column>
        <el-table-column prop="message" label="日志内容" min-width="300">
          <template #default="{ row }">
            <div class="log-message" :class="{ 'error': row.level === 'error' }">
              {{ row.message }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center">
          <template #default="{ row }">
            <el-button size="small" type="info" @click="viewLogDetail(row)">
              <i class="fas fa-eye mr-1"></i>详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[20, 50, 100, 200]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalLogs"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 系统监控 -->
    <div class="monitor-section">
      <div class="section-header">
        <h2 class="section-title">系统监控</h2>
      </div>
      
      <div class="monitor-grid">
        <!-- CPU使用率 -->
        <div class="monitor-card">
          <div class="monitor-header">
            <h3 class="monitor-title">CPU使用率</h3>
            <div class="monitor-value">{{ systemInfo.cpu }}%</div>
          </div>
          <div class="progress-bar">
            <div class="progress-fill" :style="{ width: systemInfo.cpu + '%' }"></div>
          </div>
        </div>

        <!-- 内存使用率 -->
        <div class="monitor-card">
          <div class="monitor-header">
            <h3 class="monitor-title">内存使用率</h3>
            <div class="monitor-value">{{ systemInfo.memory }}%</div>
          </div>
          <div class="progress-bar">
            <div class="progress-fill memory" :style="{ width: systemInfo.memory + '%' }"></div>
          </div>
        </div>

        <!-- 磁盘使用率 -->
        <div class="monitor-card">
          <div class="monitor-header">
            <h3 class="monitor-title">磁盘使用率</h3>
            <div class="monitor-value">{{ systemInfo.disk }}%</div>
          </div>
          <div class="progress-bar">
            <div class="progress-fill disk" :style="{ width: systemInfo.disk + '%' }"></div>
          </div>
        </div>

        <!-- 网络负载 -->
        <div class="monitor-card">
          <div class="monitor-header">
            <h3 class="monitor-title">网络负载</h3>
            <div class="monitor-value">{{ systemInfo.network }}MB/s</div>
          </div>
          <div class="network-stats">
            <div class="network-item">
              <span class="network-label">上行:</span>
              <span class="network-value">{{ systemInfo.upload }}MB/s</span>
            </div>
            <div class="network-item">
              <span class="network-label">下行:</span>
              <span class="network-value">{{ systemInfo.download }}MB/s</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 日志详情对话框 -->
    <el-dialog v-model="showDetailDialog" title="日志详情" width="800px">
      <div v-if="selectedLog" class="log-detail">
        <div class="detail-row">
          <span class="detail-label">时间:</span>
          <span class="detail-value">{{ selectedLog.timestamp }}</span>
        </div>
        <div class="detail-row">
          <span class="detail-label">级别:</span>
          <el-tag :type="getLevelType(selectedLog.level)">{{ getLevelText(selectedLog.level) }}</el-tag>
        </div>
        <div class="detail-row">
          <span class="detail-label">模块:</span>
          <span class="detail-value">{{ getModuleText(selectedLog.module) }}</span>
        </div>
        <div class="detail-row">
          <span class="detail-label">用户:</span>
          <span class="detail-value">{{ selectedLog.user }}</span>
        </div>
        <div class="detail-row">
          <span class="detail-label">操作:</span>
          <span class="detail-value">{{ selectedLog.action }}</span>
        </div>
        <div class="detail-row">
          <span class="detail-label">IP地址:</span>
          <span class="detail-value">{{ selectedLog.ip }}</span>
        </div>
        <div class="detail-row full">
          <span class="detail-label">日志内容:</span>
          <div class="detail-message">{{ selectedLog.message }}</div>
        </div>
        <div v-if="selectedLog.stackTrace" class="detail-row full">
          <span class="detail-label">堆栈信息:</span>
          <pre class="stack-trace">{{ selectedLog.stackTrace }}</pre>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDetailDialog = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'

export default {
  name: 'LogManagement',
  setup() {
    const loading = ref(false)
    const searchQuery = ref('')
    const levelFilter = ref('')
    const moduleFilter = ref('')
    const dateRange = ref([])
    const currentPage = ref(1)
    const pageSize = ref(50)
    const autoRefresh = ref(false)
    const showDetailDialog = ref(false)
    const selectedLog = ref(null)
    let refreshTimer = null
    
    const stats = reactive({
      totalLogs: 36580,
      todayLogs: 1876,
      errorLogs: 23,
      activeUsers: 286
    })
    
    const systemInfo = reactive({
      cpu: 45,
      memory: 68,
      disk: 32,
      network: 12.5,
      upload: 5.2,
      download: 7.3
    })
    
    const logs = ref([
      {
        id: 1,
        timestamp: '2024-02-16 16:35:25',
        level: 'info',
        module: 'case',
        user: '张先生',
        action: '交通事故案件提交',
        ip: '192.168.1.100',
        message: '沪C88976追尾事故案件成功提交',
        stackTrace: null
      },
      {
        id: 2,
        timestamp: '2024-02-16 16:28:15',
        level: 'info',
        module: 'case',
        user: '李卫民律师',
        action: '案件审核',
        ip: '192.168.1.101',
        message: '交通事故案件审核通过，开始处理流程',
        stackTrace: null
      },
      {
        id: 3,
        timestamp: '2024-02-16 16:25:42',
        level: 'warning',
        module: 'system',
        user: '系统',
        action: '伤残鉴定上传',
        ip: '127.0.0.1',
        message: '伤残鉴定报告文件大小超过10MB，已压缩处理',
        stackTrace: null
      },
      {
        id: 4,
        timestamp: '2024-02-16 16:20:18',
        level: 'info',
        module: 'user',
        user: '王志强律师',
        action: '保险理赔审核',
        ip: '192.168.1.50',
        message: '平安保险理赔方案审核完成',
        stackTrace: null
      },
      {
        id: 5,
        timestamp: '2024-02-16 16:15:33',
        level: 'info',
        module: 'case',
        user: '陈红律师',
        action: '案件结案',
        ip: '192.168.1.52',
        message: '交通事故人身损害赔偿案件成功结案',
        stackTrace: null
      },
      {
        id: 6,
        timestamp: '2024-02-16 16:10:28',
        level: 'error',
        module: 'system',
        user: '系统',
        action: '支付处理',
        ip: '127.0.0.1',
        message: '保险理赔支付接口调用失败，正在重试',
        stackTrace: 'Error: Payment gateway timeout\n  at PaymentService.process()\n  at async processInsuranceClaim()'
      }
    ])
    
    const filteredLogs = computed(() => {
      return logs.value.filter(log => {
        const matchesSearch = !searchQuery.value || 
          log.user.includes(searchQuery.value) ||
          log.action.includes(searchQuery.value) ||
          log.message.includes(searchQuery.value) ||
          log.ip.includes(searchQuery.value)
        
        const matchesLevel = !levelFilter.value || log.level === levelFilter.value
        const matchesModule = !moduleFilter.value || log.module === moduleFilter.value
        
        let matchesDate = true
        if (dateRange.value && dateRange.value.length === 2) {
          const logDate = new Date(log.timestamp)
          const startDate = new Date(dateRange.value[0])
          const endDate = new Date(dateRange.value[1])
          matchesDate = logDate >= startDate && logDate <= endDate
        }
        
        return matchesSearch && matchesLevel && matchesModule && matchesDate
      })
    })
    
    const totalLogs = computed(() => filteredLogs.value.length)
    
    const getLevelType = (level) => {
      const types = {
        'info': 'primary',
        'warning': 'warning',
        'error': 'danger',
        'debug': 'info'
      }
      return types[level] || 'info'
    }
    
    const getLevelText = (level) => {
      const texts = {
        'info': '信息',
        'warning': '警告',
        'error': '错误',
        'debug': '调试'
      }
      return texts[level] || '未知'
    }
    
    const getModuleText = (module) => {
      const texts = {
        'user': '用户管理',
        'case': '案件管理',
        'system': '系统管理',
        'auth': '认证授权'
      }
      return texts[module] || '未知'
    }
    
    const handleSearch = () => {
      currentPage.value = 1
    }
    
    const handleSizeChange = (size) => {
      pageSize.value = size
      currentPage.value = 1
    }
    
    const handleCurrentChange = (page) => {
      currentPage.value = page
    }
    
    const refreshData = () => {
      loading.value = true
      setTimeout(() => {
        loading.value = false
        alert('数据已刷新')
      }, 1000)
    }
    
    const clearLogs = () => {
      if (confirm('确定要清空所有日志吗？此操作不可恢复！')) {
        alert('日志清空功能开发中...')
      }
    }
    
    const exportLogs = () => {
      alert('导出日志功能开发中...')
    }
    
    const viewLogDetail = (log) => {
      selectedLog.value = log
      showDetailDialog.value = true
    }
    
    const startAutoRefresh = () => {
      if (autoRefresh.value) {
        refreshTimer = setInterval(() => {
          // 模拟获取新日志
          console.log('自动刷新日志...')
        }, 5000)
      } else {
        if (refreshTimer) {
          clearInterval(refreshTimer)
          refreshTimer = null
        }
      }
    }
    
    onMounted(() => {
      // 模拟系统信息更新
      setInterval(() => {
        systemInfo.cpu = Math.floor(Math.random() * 100)
        systemInfo.memory = Math.floor(Math.random() * 100)
        systemInfo.disk = Math.floor(Math.random() * 100)
        systemInfo.network = (Math.random() * 20).toFixed(1)
        systemInfo.upload = (Math.random() * 10).toFixed(1)
        systemInfo.download = (Math.random() * 15).toFixed(1)
      }, 3000)
    })
    
    onUnmounted(() => {
      if (refreshTimer) {
        clearInterval(refreshTimer)
      }
    })
    
    return {
      loading,
      searchQuery,
      levelFilter,
      moduleFilter,
      dateRange,
      currentPage,
      pageSize,
      autoRefresh,
      showDetailDialog,
      selectedLog,
      stats,
      systemInfo,
      logs,
      filteredLogs,
      totalLogs,
      getLevelType,
      getLevelText,
      getModuleText,
      handleSearch,
      handleSizeChange,
      handleCurrentChange,
      refreshData,
      clearLogs,
      exportLogs,
      viewLogDetail,
      startAutoRefresh
    }
  }
}
</script>

<style scoped>
.log-management {
  padding: 24px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-title {
  font-size: 28px;
  font-weight: bold;
  color: #1f2937;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.search-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-row {
  display: flex;
  gap: 16px;
  align-items: center;
  flex-wrap: wrap;
}

.search-input {
  flex: 1;
  min-width: 200px;
}

.level-filter,
.module-filter {
  width: 120px;
}

.date-picker {
  width: 300px;
}

.stats-section {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.stat-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 16px;
  border-left: 4px solid #e5e7eb;
}

.stat-card.total {
  border-left-color: #3b82f6;
}

.stat-card.today {
  border-left-color: #10b981;
}

.stat-card.errors {
  border-left-color: #ef4444;
}

.stat-card.active {
  border-left-color: #f59e0b;
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 8px;
  background: #f3f4f6;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: #6b7280;
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #1f2937;
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: #6b7280;
  margin-top: 4px;
}

.logs-section,
.monitor-section {
  background: white;
  border-radius: 8px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-title {
  font-size: 20px;
  font-weight: bold;
  color: #1f2937;
  margin: 0;
}

.log-message {
  font-family: 'Courier New', monospace;
  font-size: 13px;
  line-height: 1.4;
}

.log-message.error {
  color: #dc2626;
  font-weight: 500;
}

.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.monitor-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

.monitor-card {
  padding: 20px;
  background: #fafafa;
  border-radius: 8px;
  border: 1px solid #e5e7eb;
}

.monitor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.monitor-title {
  font-size: 14px;
  font-weight: 500;
  color: #6b7280;
  margin: 0;
}

.monitor-value {
  font-size: 18px;
  font-weight: bold;
  color: #1f2937;
}

.progress-bar {
  height: 8px;
  background: #f3f4f6;
  border-radius: 4px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #3b82f6, #1d4ed8);
  border-radius: 4px;
  transition: width 0.3s ease;
}

.progress-fill.memory {
  background: linear-gradient(90deg, #10b981, #059669);
}

.progress-fill.disk {
  background: linear-gradient(90deg, #f59e0b, #d97706);
}

.network-stats {
  display: flex;
  justify-content: space-between;
  margin-top: 8px;
}

.network-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.network-label {
  font-size: 12px;
  color: #6b7280;
}

.network-value {
  font-size: 14px;
  font-weight: bold;
  color: #1f2937;
}

.log-detail {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.detail-row {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.detail-row.full {
  flex-direction: column;
  align-items: stretch;
}

.detail-label {
  font-weight: 500;
  color: #374151;
  min-width: 80px;
}

.detail-value {
  color: #1f2937;
}

.detail-message {
  background: #f9fafb;
  padding: 12px;
  border-radius: 6px;
  font-family: 'Courier New', monospace;
  font-size: 13px;
  line-height: 1.4;
  border: 1px solid #e5e7eb;
}

.stack-trace {
  background: #1f2937;
  color: #f3f4f6;
  padding: 12px;
  border-radius: 6px;
  font-size: 12px;
  line-height: 1.4;
  margin: 0;
  overflow-x: auto;
}
</style> 